package com.swiftride.template;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.swiftride.properties.AppWeChatProperties;

public class AppWeChatTemplate {

    
    private final AppWeChatProperties appWeChatProperties;

    public AppWeChatTemplate(AppWeChatProperties appWeChatProperties) {
        this.appWeChatProperties = appWeChatProperties;
    }

    /**
     * 通过openidCode验证并获取openid
     *
     * @param openidCode 获取openid的code
     * @return openid
     */
    public String getOpenid(String openidCode) {
        //2.业务验证
        String url = String.format(appWeChatProperties.getOpenidUrl(), appWeChatProperties.getAppId(), appWeChatProperties.getSecret(), openidCode);

        String openidJsonStr = HttpUtil.get(url);
        if (StrUtil.isBlank(openidJsonStr)) {
            throw new RuntimeException("获取openid失败");
        }
        JSONObject openidJsonObject = JSONUtil.parseObj(openidJsonStr);
        String openid = openidJsonObject.getStr("openid");
        if (StrUtil.isBlank(openid)) {
            throw new RuntimeException("获取openid失败");
        }
        return openid;
    }

    /**
     * 通过phoneCode获取用户手机号
     *
     * @param phoneCode 获取phoneNum的code
     * @return phoneNum
     */
    public String getPhoneNum(String phoneCode) {
        String accessToken = getAccessToken();
        //通过accessToken,phoneCode获取手机号
        String phoneNumUrl = String.format(appWeChatProperties.getPhoneUrl(), accessToken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("code", phoneCode);
        String phoneNumJsonStr = HttpUtil.post(phoneNumUrl, jsonObject.toString());
        JSONObject phoneNumJsonObject = JSONUtil.parseObj(phoneNumJsonStr);
        if (0 != phoneNumJsonObject.getInt("errcode")) {
            throw new RuntimeException("获取电话信息失败");
        }
        JSONObject phoneInfojsonObject = JSONUtil.parseObj(phoneNumJsonObject.get("phone_info"));
        String phoneNumber = phoneInfojsonObject.getStr("phoneNumber");
        if (StrUtil.isBlank(phoneNumber)) {
            throw new RuntimeException("获取电话号码失败");
        }
        return phoneNumber;
    }

    public String getAccessToken() {
        //获取accessToken
        String accessTokenUrl = String.format(appWeChatProperties.getAccessTokenUrl(), appWeChatProperties.getAppId(), appWeChatProperties.getSecret());
        String accessTokenJsonStr = HttpUtil.get(accessTokenUrl);
        JSONObject accessTokenJsonObject = JSONUtil.parseObj(accessTokenJsonStr);
        String accessToken = accessTokenJsonObject.getStr("access_token");
        if (StrUtil.isBlank(accessToken)) {
            throw new RuntimeException("获取token信息失败");
        }
        return accessToken;
    }
}
